package com.sgb.kjwl.view.ui.activity.transport;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;


import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityLoadingAndUnloadingPlaceBinding;
import com.sgb.kjwl.di.transport.DaggerTransportComponent;
import com.sgb.kjwl.di.transport.TransportModule;
import com.sgb.kjwl.model.entity.transport.OperateGoodsSourcePlaceVO;
import com.sgb.kjwl.model.entity.transport.common.AddressItem;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.ui.adapter.transport.LoadingAndUnloadingPlaceAdapter;
import com.sgb.kjwl.view.widget.transport.MapNavigationDialog;
import com.sgb.kjwl.viewmodel.transport.LoadingAndUnloadingPlaceViewModel;
import com.swgk.core.base.di.AppComponent;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * @author: 杨畔
 * @date: 3/8/21 2:41 PM
 * @Description: 装卸地位置
 */
public class LoadingAndUnloadingPlaceActivity extends AppActivity implements AMap.OnMarkerClickListener {

    @Inject
    LoadingAndUnloadingPlaceViewModel mViewModel;
    private ActivityLoadingAndUnloadingPlaceBinding mBinding;
    //装卸地列表
    private List<AddressItem> mList;
    private LoadingAndUnloadingPlaceAdapter mAdapter;
    //地图导航弹窗
    private MapNavigationDialog mNavigationDialog;
    //地图控制器
    private AMap aMap;
    //marker集合
    private final List<Marker> mMarkers = new ArrayList<>();
    //当前最后一个点击的marker
    private Marker mLastMarker;

    /**
     * 跳转装卸地位置
     */
    public static void start(@NonNull Context context, int index, @NonNull String loadMode, @NonNull OperateGoodsSourcePlaceVO place) {
        Intent intent = new Intent(context, LoadingAndUnloadingPlaceActivity.class);
        intent.putExtra(RouterKey.TYPE, loadMode);
        intent.putExtra(RouterKey.INT, index);
        intent.putExtra(RouterKey.DATA, place);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerTransportComponent.builder()
                .appComponent(appComponent)
                .transportModule(new TransportModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_loading_and_unloading_place);
        mBinding.setLifecycleOwner(this);
        mBinding.mapLoadingAndUnloadingPlace.onCreate(savedInstanceState);
        initMap();
        initPopup();
        initRecycler();
        initEvent();
        initData();
    }

    private void initPopup() {
        //导航弹窗初始化
        mNavigationDialog = new MapNavigationDialog(this);
    }

    /**
     * 初始化地图
     */
    private void initMap() {
        //获取地图控制类
        aMap = mBinding.mapLoadingAndUnloadingPlace.getMap();
        //显示定位蓝点
        aMap.getUiSettings().setMyLocationButtonEnabled(false);
        //显示缩放控制器
        aMap.getUiSettings().setZoomControlsEnabled(false);
        //marker点击监听
        aMap.setOnMarkerClickListener(this);
    }

    private void initRecycler() {
        mList = new ArrayList<>();
        mAdapter = new LoadingAndUnloadingPlaceAdapter(mList);
        mBinding.rvLoadingAndUnloadingPlace.setLayoutManager(new LinearLayoutManager(this));
        mAdapter.bindToRecyclerView(mBinding.rvLoadingAndUnloadingPlace);
    }

    private void initEvent() {
        mBinding.actionBar.setOnBackClickListener(view -> finish());
        mAdapter.setOnItemClickListener((adapter, view, position) -> itemClick(position));
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.tv_loading_and_unloading_place_go) {
                //地图导航弹窗
                mNavigationDialog.navigation(mList.get(position));
            }
        });
    }

    private void initData() {
        String loadMode = getIntent().getStringExtra(RouterKey.TYPE);
        int index = getIntent().getIntExtra(RouterKey.INT, 0);
        OperateGoodsSourcePlaceVO entity = (OperateGoodsSourcePlaceVO) getIntent().getSerializableExtra(RouterKey.DATA);
        //同步装卸信息
        mViewModel.syncLoadingData(this, loadMode, entity, mList);
        mAdapter.notifyDataSetChanged();
        //设置marker信息
        refreshMapMarker(mList);
        // 初次进入选中默认项
        if (index < mList.size()) {
            itemClick(index);
        }
    }

    /**
     * 装卸地点击
     */
    private void itemClick(int position) {
        // 选中marker点中状态
        onMarkerClick(mMarkers.get(position));
        //移动地图
        AddressItem entity = mList.get(position);
        cameraToPosition(entity.getLatitude(), entity.getLongitude());
    }

    /**
     * 刷新地图覆盖物
     */
    private void refreshMapMarker(List<AddressItem> list) {
        clearMarker();
        if (list == null || list.size() == 0) return;
        //添加新marker，清空历史marker
        for (AddressItem entity : list) {
            addMarker(new LatLng(entity.getLatitude(), entity.getLongitude()), entity.getMakerIcon(), entity);
        }
    }

    /**
     * 清除页面marker
     */
    private void clearMarker() {
        aMap.clear();
        mMarkers.clear();
    }

    /**
     * 添加覆盖物
     */
    private void addMarker(LatLng latLng, @DrawableRes int drawable, AddressItem entity) {
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.icon(BitmapDescriptorFactory.fromResource(drawable));
        Marker marker = aMap.addMarker(markerOption);
        //设置附着对象
        marker.setObject(entity);
        mMarkers.add(marker);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        //还原上一个marker
        if (mLastMarker != null) {
            AddressItem entity = (AddressItem) mLastMarker.getObject();
            mLastMarker.setIcon(BitmapDescriptorFactory.fromResource(entity.getMakerIcon()));
        }
        //设置marker选中
        AddressItem entity = (AddressItem) marker.getObject();
        marker.setIcon(BitmapDescriptorFactory.fromResource(entity.getBigMakerIcon()));
        mLastMarker = marker;
        //设置列表选中
        mAdapter.setIndex(entity.getPosition());
        mAdapter.notifyDataSetChanged();
        return false;
    }

    /**
     * 根据经纬度移动地图，标记中心点
     */
    private void cameraToPosition(Double lat, Double lng) {
        if (lat == 0 || lng == 0) return;
        //切换地图中心点
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 11));
    }

    @Override
    protected void onResume() {
        super.onResume();
        mBinding.mapLoadingAndUnloadingPlace.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mBinding.mapLoadingAndUnloadingPlace.onPause();
    }

    @Override
    protected void onSaveInstanceState(@NotNull Bundle outState) {
        super.onSaveInstanceState(outState);
        mBinding.mapLoadingAndUnloadingPlace.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBinding.mapLoadingAndUnloadingPlace.onDestroy();
    }
}
